package com.xuecheng.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.api.sysetm.model.dto.DictionaryDTO;
import com.xuecheng.common.util.StringUtil;
import com.xuecheng.system.convert.SystemConvert;
import com.xuecheng.system.entity.Dictionary;
import com.xuecheng.system.mapper.DictionaryMapper;
import com.xuecheng.system.service.DictionaryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class DictionaryServiceImpl extends ServiceImpl<DictionaryMapper, Dictionary> implements DictionaryService {

    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;


    @Override
    public List<DictionaryDTO> queryAll() {
        //查询redis中是否有数据没有再走数据库
        List<Dictionary> dictionaryList = new ArrayList<>();
        if (redisTemplate.hasKey("dictionary001")) {
            List<Object> objectList = redisTemplate.opsForHash().values("dictionary001");
            for (Object obj : objectList) {
                dictionaryList.add((Dictionary) obj);
            }
        }else{
            dictionaryList = this.list();
        }

        //转换
        List<DictionaryDTO> dtoList = SystemConvert.INSTANCE.entitys2Dtos(dictionaryList);

        return dtoList;
    }

    @Override
    public DictionaryDTO queryByCode(String code) {
        if (StringUtil.isBlank(code)) {
            return null;
        }
        //查询条件
        LambdaQueryWrapper<Dictionary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dictionary::getCode, code);
        //查询数据
        Dictionary dictionary = this.getOne(queryWrapper);
        DictionaryDTO dictionaryDTO = null;

        if (null == dictionary) {
            dictionaryDTO = new DictionaryDTO();
            return dictionaryDTO;
        }
        //转换
        dictionaryDTO = SystemConvert.INSTANCE.entity2Dto(dictionary);

        return dictionaryDTO;
    }
}
